package cn.jtool.dig.server.comm.tunnel.protocol;

import cn.jtool.dig.common.model.Commands;
import cn.jtool.dig.common.model.Packet;
import cn.jtool.dig.common.model.PacketBody;
import cn.jtool.dig.common.model.Session;
import cn.jtool.dig.common.netty.CtxUtils;
import cn.jtool.dig.common.netty.ProtocolProcess;
import cn.jtool.dig.common.netty.SessionManager;
import cn.jtool.dig.server.comm.MessageExchange;
import cn.jtool.dig.server.comm.StageManager;
import cn.jtool.dig.server.comm.VirtualChannelManager;
import cn.jtool.dig.server.comm.tunnel.TunnelAttrKey;
import cn.jtool.dig.server.dao.entity.License;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 通用应答
 */
@Slf4j
@Component
public class P_10_CommonResponse implements ProtocolProcess {

    @Override
    public int protocolId() {
        return Commands.COMMON_RESPONSE.getCode();
    }

    @Override
    public Packet process(ChannelHandlerContext ctx, Packet packet) {
        PacketBody body = packet.getBody();
        int commandId = body.readByte();
        Commands command = Commands.valueOfCode(commandId);
        int sn = body.readWord();
        int result = body.readByte();
        log.info("Client 通用应答: 应答指令: {}  应答流水号: {}  应答结果: {}", command.getName(), sn, result == 0 ? "成功" : "失败");

        if(command == Commands.CREATE_SESSION){
            Session session = SessionManager.getSession(packet.getHeader().getChannelId());
            if(Objects.nonNull(session)){
                if(result == 0x00){
                    License license = CtxUtils.getAttribute(ctx, TunnelAttrKey.LICENSE);
                    VirtualChannelManager.addVirtualChannel(packet.getHeader().getChannelId(), license.getId());

                    List<Packet> packets = StageManager.getStageAndRemove(packet.getHeader().getChannelId());
                    if(CollectionUtils.isNotEmpty(packets)){
                        packets.forEach(MessageExchange::upData);
                    }
                }else{
                    session.disconnect();
                }
            }
        }

        if(command == Commands.DATA_TRANSPARENT && result == 0x01){
            log.info("[tunnel]收到数据透传应答: {} {} {}", command, sn, "失败");
            Session session = SessionManager.getSession(packet.getHeader().getChannelId());
            if(Objects.nonNull(session)){
                session.disconnect();
            }
        }

        return null;
    }
}
